﻿using Authority.Model;
using Common.Library;
using Common.Model;
using Container.Library;
using Dapper.Library;
using Dapper.Library.DataAccessSql;
using Dapper.PostgreSql.Library;
using Serialize.Library;
using System;
using System.Collections.Generic;
using System.Linq;

/*
* 命名空间: Authority.Logic
*
* 功 能： 图层功能管理逻辑
*
* 类 名： SysPostServiceImpl
*
* Version   变更日期            负责人     变更内容
* ─────────────────────────────────────────────────
* V1.0.1    2020/03/17 14:34:43 李聪     创建
* V1.0.2    2020/03/18 11:12:00 罗维     增加权限相关操作
*
* Copyright (c) 2020 Lir Corporation. All rights reserved.
*/

namespace Authority.Logic
{
    /// <summary>
    /// 图层功能管理逻辑
    /// </summary>
    public class LayertreeCfgServiceImpl:OperationLogicImpl, ILayertreeCfgService
    {
        #region 图层基础管理操作
        #region 查询
        /// <summary>
        /// 查询所有的图层
        /// </summary>
        /// <returns></returns>
       public ResultJsonInfo<List<LayertreeResponse>> LoadList(ParametersInfo<string> parameters)
        {
            var resultInfo = new ResultJsonInfo<List<LayertreeResponse>>();
            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var result = con.QuerySet<SysLayertreeCfgEntity>();

                if (parameters.parameters.IsNotNullOrEmpty())
                {
                    result.Where(p => p.name.Contains(parameters.parameters) || p.featureclass_name.Contains(parameters.parameters) || p.memo.Contains(parameters.parameters) || p.tablename.Contains(parameters.parameters));
                }
                var queryInfo = result.Where(p => p.is_deleted == false).OrderBy(p => p.sort).PageList(parameters.page, parameters.limit);

                if (queryInfo.Items.Count > 0)
                {
                    var menusList = queryInfo.Items.MapToList<LayertreeResponse>();

                    ///这里获取所有，查询是否有兄弟节点
                    var functionListInfoAll = result.Where(p => p.is_deleted == false)
                         .OrderBy(p => p.sort).ToList();
                    foreach (var item in menusList)
                    {
                        //NET算术运算溢出问题
                        item.have_elder = functionListInfoAll.Exists(p => p.sort < item.sort && p.id != item.id && p.parent_id == item.parent_id);
                        item.have_younger = functionListInfoAll.Exists(p => p.sort > item.sort && p.id != item.id && p.parent_id == item.parent_id);
                    }
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = menusList;
                    resultInfo.Count = queryInfo.Total;
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "无对应值存在！";
                }
            }

            return resultInfo;
        }

        /// <summary>
        /// 查询单个图层的信息
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public ResultJsonInfo<LayertreeResponse> LoadSinger(string layertId)
        {
            var resultInfo = new ResultJsonInfo<LayertreeResponse>();
            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {

                var result = con.QuerySet<SysLayertreeCfgEntity>().Where(a => a.id == layertId).Get();
                if (result != null)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result.MapTo<LayertreeResponse>();

                }
                else
                {
                    resultInfo.Msg = "不存在对应信息";
                }
            }


            return resultInfo;
        }
        #endregion

        #region 修改
        /// <summary>
        /// 修改图层
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Modify(LayertreeCfgModifyAddRequest request)
        {

            var resultInfo = new ResultJsonInfo<int>();
            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var sysLayertreeCfg = con.QuerySet<SysLayertreeCfgEntity>().Where(a => a.id == request.id).Get();
                if (sysLayertreeCfg == null)
                {
                    resultInfo.Code = ActionCodes.ArgumentInvalid;
                    resultInfo.Msg = "图层不存在！";
                    return resultInfo;
                }
               sysLayertreeCfg.name = request.name;
                sysLayertreeCfg.tablename = request.tablename;
                sysLayertreeCfg.is_valid = request.is_valid;
                sysLayertreeCfg.featureclass_name = request.featureclass_name;
               sysLayertreeCfg.memo = request.memo;
                var user = GetLoginUserInfo();
                sysLayertreeCfg.modifier_date = DateTime.Now;
                sysLayertreeCfg.modifier_id = user.id;
                sysLayertreeCfg.modifier_name = user.name;
                var result = con.CommandSet<SysLayertreeCfgEntity>().Update(sysLayertreeCfg);

                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "修改成功！";

                    AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.LayerManage, $"修改图层成功，修改图层信息：{JsonHelper.ToJson(sysLayertreeCfg)}");
                }
                else
                {
                    resultInfo.Msg = "修改失败！";
                }
            }

            return resultInfo;

        }
        /// <summary>
        /// 删除图层
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> layertId)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                var gIds = layertId.ToArray();
                var userGroups = con.QuerySet<SysLayertreeCfgEntity>().Where(a => a.id.PostIn(gIds)).ToList();
                var result = 0;
                var user = GetLoginUserInfo();
                foreach (var item in userGroups)
                {
                    item.is_deleted = true;
                    item.modifier_date = DateTime.Now;
                    item.modifier_id = user.id;
                    item.modifier_name = user.name;

                    result = con.CommandSet<SysLayertreeCfgEntity>().Update(item);
                }
                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "删除成功！";
                    AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.LayerManage, $"删除图层成功，删除图层信息：{JsonHelper.ToJson(layertId)}");
                }
                else
                {
                    resultInfo.Msg = "删除失败！";
                }
            }

            return resultInfo;

        }
        /// <summary>
        /// 启用/禁用图层
        /// </summary>
        /// <param name="layertId"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ForbidOrEnable(string layertId)
        {
            var resultInfo = new ResultJsonInfo<int>();
            if (!string.IsNullOrEmpty(layertId))
            {
                using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
                {
                    var result = 0;
                    var sysDepartmentInfolist = con.QuerySet<SysLayertreeCfgEntity>().Where(p => p.is_deleted == false).ToList();

                    var list = GetSons(sysDepartmentInfolist, layertId);
                    var sysDepartmentInfo = con.QuerySet<SysLayertreeCfgEntity>().Where(p => p.id == layertId).Get(); ;


                    if (list.Count > 0 && sysDepartmentInfo != null)
                    {   //获取登录用户信息
                        var userLoginInfo = GetLoginUserInfo();
                        if (sysDepartmentInfo.is_valid)
                        {
                            foreach (SysLayertreeCfgEntity item in list)
                            {
                                item.is_valid = item.is_valid == true ? false : false;
                                item.modifier_id = userLoginInfo.id;
                                item.modifier_name = userLoginInfo.name;

                                result += con.CommandSet<SysLayertreeCfgEntity>().Update(item);
                            }
                        }
                        else
                        {
                            sysDepartmentInfo.is_valid = !sysDepartmentInfo.is_valid;
                            sysDepartmentInfo.modifier_id = userLoginInfo.id;
                            sysDepartmentInfo.modifier_name = userLoginInfo.name;

                            result += con.CommandSet<SysLayertreeCfgEntity>().Update(sysDepartmentInfo);

                        }
                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Data = result;
                            resultInfo.Msg = "禁用/启用部门成功！";

                            AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.DepartmentManage, $"禁用/启用部门:{JsonHelper.ToJson(sysDepartmentInfo)}");
                        }
                        else
                        {
                            resultInfo.Msg = "操作失败！";
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "无对应信息！";
                    }

                }
            }

            return resultInfo;

        }

        #endregion

        #region 获取子节点信息

        private List<SysLayertreeCfgEntity> GetSons(List<SysLayertreeCfgEntity> list, string parent_id)
        {
            var query = list.Where(p => p.id == parent_id).ToList();
            var list2 = query.Concat(GetSonList(list, parent_id)).ToList();
            return list2;
        }

        private IEnumerable<SysLayertreeCfgEntity> GetSonList(List<SysLayertreeCfgEntity> list, string parent_id)
        {
            var query = list.Where(p => p.parent_id == parent_id).ToList();
            return query.ToList().Concat(query.ToList().SelectMany(t => GetSonList(list, t.id)));
        }
        #endregion
        #region 新增
        /// <summary>
        /// 新增子节点
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Addnode(LayertreeCfgChildAddRequest request)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                if (request.parent_id != "" && request.parent_id != null)
                {
                    con.Transaction(tran =>
                    {
                        var result = 0;
                        var user = GetLoginUserInfo();
                        var sysLayertrees = tran.QuerySet<SysLayertreeCfgEntity>().ToList();

                        var sysLayertreeCfg = sysLayertrees.Find(p => p.id == request.parent_id);
                        if (sysLayertreeCfg != null)
                        {
                            //查询出排序在该节点之后的所有节点
                            var sysUserGroupInfos = sysLayertrees.FindAll(p => p.sort > sysLayertreeCfg.sort);
                            foreach (var item in sysUserGroupInfos)
                            {
                                item.sort = item.sort + 1;
                                tran.CommandSet<SysLayertreeCfgEntity>().Update(item);
                            }
                            var cfgEntity = request.MapTo<SysLayertreeCfgEntity>();

                            cfgEntity.modifier_date = DateTime.Now;
                            cfgEntity.modifier_name = user.name;
                            cfgEntity.modifier_id = user.id;
                            cfgEntity.create_date = DateTime.Now;
                            cfgEntity.creator_name = user.name;
                            cfgEntity.creator_id = user.id;
                            cfgEntity.sort = sysLayertreeCfg.sort + 1;
                            result = tran.CommandSet<SysLayertreeCfgEntity>().Insert(cfgEntity);

                            if (result > 0)
                            {
                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Data = result;
                                resultInfo.Msg = "新增子节点信息成功！";
                                AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.LayerManage, $"新增子节点信息成功，新增子节点信息：{JsonHelper.ToJson(cfgEntity)}");
                            }
                            else
                            {
                                resultInfo.Msg = "操作失败！";
                            }
                        }
                        else
                        {
                            resultInfo.Msg = "无对应父节点信息！";
                        }
                    });

                }
                else {
                    var user = GetLoginUserInfo();

                    var result = 0;

                    var layertreeCfgEntity = request.MapTo<SysLayertreeCfgEntity>();
                    //获取所有图层信息
                    var maxSort = con.QuerySet<SysLayertreeCfgEntity>().Max(p => p.sort);
                    layertreeCfgEntity.parent_id = "";
                    layertreeCfgEntity.sort = maxSort + 1;
                    layertreeCfgEntity.creator_id = user.id;
                    layertreeCfgEntity.creator_name = user.name;
                    layertreeCfgEntity.modifier_id = user.id;
                    layertreeCfgEntity.modifier_name = user.name;
                    result = con.CommandSet<SysLayertreeCfgEntity>().Insert(layertreeCfgEntity);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "新增根节点信息成功！";
                        AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.LayerManage, $"新增根节点信息成功，新增根节点信息：{JsonHelper.ToJson(layertreeCfgEntity)}");
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                }
               
            }
            return resultInfo;
        }

        #endregion

        #region 移动顺序
        /// <summary>
        /// 移动顺序操作
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Move(LayertreeCfgMoveRequest inputInfo)
        {
            var result = new ResultJsonInfo<int>();
            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                con.Transaction(tran =>
                {
                    var adminlayertree = tran.QuerySet<SysLayertreeCfgEntity>().OrderBy(p => p.sort).ToList();
              
                    SysLayertreeCfgEntity currAdminlayertree = adminlayertree.Find(p => p.id == inputInfo.id);
             
                    List<SysLayertreeCfgEntity> brothersAdminlayertree = adminlayertree.FindAll(p => p.parent_id == currAdminlayertree.parent_id);

                    SysLayertreeCfgEntity broAdminlayertree = null;
                    foreach (SysLayertreeCfgEntity item in brothersAdminlayertree)
                    {
                        if (inputInfo.Flag == 1)//上移
                        {
                            if (item.sort < currAdminlayertree.sort)
                            {
                                broAdminlayertree = item;
                            }
                            if (item.sort > currAdminlayertree.sort)
                            {
                                break;
                            } //找到上一个兄弟节点
                        }
                        else //下移
                        {
                            if (item.sort > currAdminlayertree.sort) { broAdminlayertree = item; break; } //找到下一个兄弟节点
                        }
                    }

                    List<SysLayertreeCfgEntity> currFuns = new List<SysLayertreeCfgEntity>();
                    currFuns.Add(currAdminlayertree);
                    GetMoveNode(adminlayertree, currAdminlayertree.id, currFuns);

                    List<SysLayertreeCfgEntity> moveFuns = new List<SysLayertreeCfgEntity>();
                    moveFuns.Add(broAdminlayertree);
                    GetMoveNode(adminlayertree, broAdminlayertree.id, moveFuns);

                    //上移
                    if (inputInfo.Flag == 1)
                    {
                        foreach (SysLayertreeCfgEntity item in currFuns)
                        {
                            item.sort = short.Parse((item.sort - short.Parse(moveFuns.Count.ToString())).ToString());
                            tran.CommandSet<SysLayertreeCfgEntity>().Update(item);
                        }

                        foreach (SysLayertreeCfgEntity item in moveFuns)
                        {
                            item.sort = short.Parse((item.sort + short.Parse(currFuns.Count.ToString())).ToString());
                            tran.CommandSet<SysLayertreeCfgEntity>().Update(item);
                        }
                    }
                    else
                    {
                        foreach (SysLayertreeCfgEntity item in currFuns)
                        {
                            item.sort = short.Parse((item.sort + short.Parse(moveFuns.Count.ToString())).ToString());
                            tran.CommandSet<SysLayertreeCfgEntity>().Update(item);
                        }
                        foreach (SysLayertreeCfgEntity item in moveFuns)
                        {
                            item.sort = short.Parse((item.sort - short.Parse(currFuns.Count.ToString())).ToString());
                            tran.CommandSet<SysLayertreeCfgEntity>().Update(item);
                        }
                    }
                });
                result.Code = ActionCodes.Success;
                result.Data = 1;

                AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.DepartmentManage, $"移动顺序操作:{JsonHelper.ToJson(inputInfo)}");
            }
            return result;
        }

        /// <summary>
        /// 上下一定子功能（递归）
        /// </summary>
        /// <param name="adminDepartments"></param>
        /// <param name="funId"></param>
        /// <param name="move"></param>
        private void GetMoveNode(List<SysLayertreeCfgEntity> adminDepartments, string funId, List<SysLayertreeCfgEntity> move)
        {
            List<SysLayertreeCfgEntity> borgs = adminDepartments.FindAll(r => r.parent_id == funId);
            foreach (SysLayertreeCfgEntity item in borgs)
            {
                if (item.parent_id == funId)
                {
                    move.Add(item);
                    List<SysLayertreeCfgEntity> tempFuns = adminDepartments.FindAll(r => r.parent_id == item.id);
                    if (tempFuns != null && tempFuns.Count > 0)
                    {
                        GetMoveNode(adminDepartments, item.id, move);
                    }
                }
            }
        }
        #endregion
        #endregion

        #region 权限管理相关模块
        /// <summary>
        /// 根据角色ID，获取所有可操作图层已赋权限情况
        /// </summary>
        /// <param name="queryInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<LayertreeCfgRoleLayerResponse>> LoadListInfoByRoleId(LayertreeCfgRoleQueryRequest queryInfo)
        {
            var resultInfo = new ResultJsonInfo<List<LayertreeCfgRoleLayerResponse>>();
            var layerList = new List<LayertreeCfgRoleLayerResponse>();

            List<SysLayertreeCfgEntity> listInfo = null;
            List<SysRolePermissionReEntity> sysRoleLayer = null;

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {

                con.Transaction(tran =>
                {
                    listInfo = tran.QuerySet<SysLayertreeCfgEntity>()
                              .Where(p => p.is_deleted == false && p.is_valid == true)
                              .OrderBy(p => p.sort)
                              .ToList();

                    int permissionType = (int)PermissionType.Layertree;
                    sysRoleLayer = tran.QuerySet<SysRolePermissionReEntity>()
                        .Join<SysRolePermissionReEntity, SysLayertreeCfgEntity>((a, b) => a.permission_id == b.id)
                        .From<SysRolePermissionReEntity, SysLayertreeCfgEntity>()
                        .OrderBy<SysLayertreeCfgEntity>(p => p.sort)
                        .Where((a, b) => a.permission_type.Equals(permissionType) && b.is_valid == true && a.role_id == queryInfo.roleId)
                        .ToList((a, b) => new SysRolePermissionReEntity
                        {
                            id = a.id,
                            role_id = a.role_id,
                            permission_id = a.permission_id,
                            permission_type = a.permission_type
                        });

                    layerList = listInfo.MapToList<LayertreeCfgRoleLayerResponse>();

                    foreach (var item in layerList)
                    {
                        if (sysRoleLayer.Exists(p => p.permission_id == item.id))
                        {
                            item.lay_is_checked = true;
                        }
                    }
                });
            }

            if (listInfo.Count > 0)
            {
                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = layerList;
                resultInfo.Count = layerList.Count;
                resultInfo.Msg = "获取成功！";
            }
            else
            {
                resultInfo.Msg = "无对应信息！";
            }
            return resultInfo;
        }


        /// <summary>
        /// 修改对应角色赋值的图层操作权限
        /// </summary>
        /// <param name="modifyInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ModifyRoleLayerInfo(LayertreeCfgRoleModifyRequest modifyInfo) {

            var resultInfo = new ResultJsonInfo<int>();

            using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
            {
                con.Transaction(tran =>
                {
                    var layerCodes = modifyInfo.layerIdList;

                    #region 获取当前选中节点和选中节点的子节点
                    var allInfo = tran.QuerySet<SysLayertreeCfgEntity>().Where(p => p.is_deleted == false && p.is_valid == true)
                                                                .OrderBy(p => p.sort)
                                                                .ToList();
                    var rootInfo = allInfo.FindAll(p => layerCodes.Contains(p.id));

                    var listInfo = new List<SysLayertreeCfgEntity>();
                    if (rootInfo.Count > 0)
                    {
                        listInfo.AddRange(rootInfo);
                        listInfo.AddRange(allInfo.GetParentList(rootInfo));
                    }
                    layerCodes = listInfo.Select(t => t.id).Distinct().ToList();

                    #endregion
                    int permissionType = (int)PermissionType.Layertree;
                    //获取该角色原有的图层权限
                    var roleLayerListInfo = tran.QuerySet<SysRolePermissionReEntity>()
                                    .Where(p => p.role_id.Equals(modifyInfo.roleid)&&p.permission_type.Equals(permissionType))
                                    .ToList();

                    //1、获取需要删除的，删除掉。
                    var needRemoveRoleLayerListInfo = roleLayerListInfo.FindAll(p => !layerCodes.Contains(p.permission_id))
                                    .Select(p => p.permission_id)
                                    .ToArray();

                    //删除掉不用的图层
                    tran.CommandSet<SysRolePermissionReEntity>()
                                    .Where(p => p.permission_id.PostIn(needRemoveRoleLayerListInfo) && p.role_id.Equals(modifyInfo.roleid))
                                    .Delete();

                    //2、获取需要增加的，增加上。
                    var needAddRoleLayerListInfo = layerCodes.ToList()
                                    .FindAll(p => !roleLayerListInfo.Select(roleMenu => roleMenu.permission_id).Contains(p));

                    SysRolePermissionReEntity roleMenuItem = null;
                    foreach (var item in needAddRoleLayerListInfo)
                    {
                        roleMenuItem = new SysRolePermissionReEntity();
                        roleMenuItem.id = GuidHelper.GetGuid();
                        roleMenuItem.role_id = modifyInfo.roleid;
                        roleMenuItem.permission_id = item;
                        roleMenuItem.permission_type = (int)PermissionType.Layertree;
                        tran.CommandSet<SysRolePermissionReEntity>().Insert(roleMenuItem);
                    }
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = 1;
                    resultInfo.Msg = "操作成功！";
                });
            }
            return resultInfo;
        }
        #endregion
    }
}
